/**
 * Copyright (c) 2009  Collaborative Development Group, C.S. Dept., University of Bari
 *
 * All rights reserved. This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License v1.0  which accompanies this distribution, and is 
 * available at http://www.eclipse.org/legal/epl-v10.html
 */
package it.uniba.di.cdg.penelope.ui.job;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;

/**
 * This aspect is an interceptor for executing methods annotated with {@link RunAsJob} using the Eclipse {@link Job} API.
 */
@Aspect
public abstract class AbstractJobExecutionAspect {
	
	@Pointcut( "" )
	public abstract void scope();
	
	@Pointcut( "execution( @it.uniba.di.cdg.penelope.ui.job.RunAsJob void *(..)) && @annotation( ann )" )
	protected void onAnnotatedMethod( RunAsJob ann ) { }
	
	@Around( "onAnnotatedMethod( ann )" )
	public final void afterActivation( RunAsJob ann, final ProceedingJoinPoint pjp ) {
		Job job = new Job( ann.value() ) {
			@Override
			protected IStatus run( IProgressMonitor monitor ) {
				try {
					pjp.proceed();
				} catch (Throwable e) {
					throw new JobExecutionException( e.getCause() );
				}
				
				return Status.OK_STATUS;
			}
		}; 
		job.schedule();
	}
}
